<template>
  <div class="product-template-view-container" >

    <!-- start 顶部工具栏 -->
    <div class="product-template-toolbar">
      <div class="product-template-toolbar-left" v-if="allowBack || !isDelete">
        <el-button type="plain-third" @click="goBack" v-if="allowBack"><i class="iconfont icon-arrow-left"></i>{{$t('common.base.back')}}</el-button>
        <template v-if="!isDelete">
          <el-button
            type="plain-third"
            @click="goEdit"
            v-track="getBtnsTrackData('TO_EDIT')"
            v-if="allowEditProduct"><i class="iconfont icon-edit-square"></i>{{$t('common.base.edit')}}</el-button>
          <el-button
            type="plain-third"
            @click="deleteProductTemplate"
            v-track="getBtnsTrackData('DELETE')"
            v-if="allowDeleteProductTemplate"><i class="iconfont icon-delete"></i>{{$t('common.base.delete')}}</el-button>
        </template>
      </div>
    </div>
    <!-- end 顶部工具栏 -->

    <!-- start 详情平铺布局 -->
    <div v-loading="loading" v-if="viewLayout === 1" class="base-detail-tile-layout product-template-detail">
      <BaseTileLayoutTabBar
        :bar-list="layoutTabBarList"
        :now-item="leftActiveTab"
        @changeItem="tabBarChangeItem"
        @openLayoutModal="openBaseLayoutModal"
      ></BaseTileLayoutTabBar>
      <!-- left form表单展示 -->
      <form-view 
        v-show="leftActiveTab == 'view-detail'" 
        :form-cell-count="formCellCount" 
        class="bbx-cell-form-view" 
        :fields="fields" 
        :value="productTemplate"
      >
        <!-- start 创建人 -->
        <template slot="createUser" slot-scope="{value}">
          <div class="form-view-row bbx-form-cell-item" v-if="value">
            <label>{{$t('common.base.createUser')}}</label>
            <div class="form-view-row-content">
            <span v-user="value.userId" class="user-card-triggle">
              <template v-if="isOpenData">
                <open-data type='userName' :openid="value.staffId"></open-data>
              </template>
              <template v-else>
                <span>{{ value.displayName || '' }}</span>
              </template>
            </span>
            </div>
          </div>
        </template>
        <!-- end 创建人 -->

        <!-- start 创建时间 -->
        <template slot="createTime" slot-scope="{value}">
          <div class="form-view-row bbx-form-cell-item" v-if="value">
            <label>{{$t('common.base.createTime')}}</label>
            <div class="form-view-row-content">
              <span>{{ value | fmt_datetime }}</span>
            </div>
          </div>
        </template>
        <!-- end 创建时间 -->
        <!-- start 产品类型 -->
        <template slot="catalogId" slot-scope="{value}">
          <div class="form-view-row bbx-form-cell-item" v-if="value">
            <label>{{$t('common.base.productType')}}</label>
            <div class="form-view-row-content">
              <span>{{ productTemplate.type }}</span>
            </div>
          </div>
        </template>
        <!-- end 产品类型 -->
      </form-view>
      <!-- left form 表单展示 -->

      <!-- right start -->
      <div v-show="leftActiveTab !== 'view-detail'" class="product-template-relation-content product-template-left-layout">
        <keep-alive>  
          <component
            :is="leftComponentTab"
            :share-data="propsForSubComponents"
            @changeRecordCount="recordCountChange"
          /></component>
        </keep-alive>
      </div>  
      
      <!-- right end -->

    </div>
    <base-collapse v-if="viewLayout === 2" v-loading="loading" class="task-detail-main-content detail-main-content" :show-collapse="showCollapse" :direction.sync="collapseDirection" :rightSize="2">
      <template slot="left">
        <div class="product-template-detail" v-if="!loading">
          <BaseTileLayoutTabBar
            :bar-list="viewLeftBarList"
            :now-item="leftActiveTab"
            :structure="2"
            @openLayoutModal="openBaseLayoutModal"
          ></BaseTileLayoutTabBar>
          <!-- start form表单展示 -->
          <form-view 
            :form-cell-count="formCellCount" 
            class="bbx-cell-form-view" 
            :fields="fields" 
            :value="productTemplate" 
            v-show="collapseDirection !== 'left'"
          >

            <!-- start 创建人 -->
            <template slot="createUser" slot-scope="{value}">
              <div class="form-view-row bbx-form-cell-item" v-if="value">
                <label>{{$t('common.base.createUser')}}</label>
                <div class="form-view-row-content">
                <span v-user="value.userId" class="user-card-triggle">
                  <template v-if="isOpenData">
                    <open-data type='userName' :openid="value.staffId"></open-data>
                  </template>
                  <template v-else>
                    <span>{{ value.displayName || '' }}</span>
                  </template>
                </span>
                </div>
              </div>
            </template>
            <!-- end 创建人 -->

            <!-- start 创建时间 -->
            <template slot="createTime" slot-scope="{value}">
              <div class="form-view-row bbx-form-cell-item" v-if="value">
                <label>{{$t('common.base.createTime')}}</label>
                <div class="form-view-row-content">
                  <span>{{ value | fmt_datetime }}</span>
                </div>
              </div>
            </template>
            <!-- end 创建时间 -->
            <!-- start 产品类型 -->
            <template slot="catalogId" slot-scope="{value}">
              <div class="form-view-row bbx-form-cell-item" v-if="value">
                <label>{{$t('common.base.productType')}}</label>
                <div class="form-view-row-content">
                  <span>{{ productTemplate.type }}</span>
                </div>
              </div>
            </template>
            <!-- end 产品类型 -->

          </form-view>
          <!-- end form 表单展示 -->
        </div>
      </template>
      <template slot="right">
        <!-- start  -->
        <div class="product-template-relation" v-show="collapseDirection !== 'right' && productTemplate.id">
          <base-tabbar
              :tabs="tabs"
              v-model="currentTab"
              @tab-click="rightActiveTabClick"></base-tabbar>
          <div class="product-template-relation-content">
            <keep-alive>
              <component
                  :is="currentTab"
                  :share-data="propsForSubComponents"
                  @changeRecordCount="recordCountChange">
              </component>
            </keep-alive>
          </div>
        </div>
        <!-- end -->
        <div class="collapse-right" v-show="collapseDirection === 'right'">
          {{ $t('product.detail.tabs.tab3')}}
        </div>
      </template>
    </base-collapse>
    <!-- end content -->

    <biz-layout-modal
      ref="bizLayoutModal"
      :biz-layout-type="baseLayout"
      :columns="formCellCount"
      @changeLayout="changeViewDetailLayout">
    </biz-layout-modal>

  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform'
import url from 'url';

import AuthUtil from '@src/util/auth';
import platform from '@src/platform';
import { useStateSystemViewLayout } from 'pub-bbx-utils'

import { getProductTemplate, productTemplateDelete, getProductFields} from '@src/api/ProductApi.js';

import ProductTemplateInfoRecord from './component/ProductTemplateInfoRecord.vue';
import ProductTemplateRelatedProductTable from './component/ProductTemplateRelatedProductTable.vue';
import BaseTileLayoutTabBar from '@src/component/common/BaseTabBar/BaseTileLayoutTabBar.vue'
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
import { RESOURCE_PREFIX } from '@src/util/linkSwitch'
import layoutMixin from '@src/mixins/layoutMixin'

export default {
  name: 'product-template-view',
  mixins: [ThemeMixin, layoutMixin],
  props: {
    initData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      isOpenData,
      currentTab: 'product-template-info-record', // 当前的tab
      loading: false, // 加载状态
      productTemplate: {
        id: ''
      }, // 产品模板数据
      productCount: 0,
      recordCount: 0,
      showWholeName: -1, // -1 代表不显示展开icon 0 代表收起 1 代表展开
      tabs: [],
      fieldsInfo: [],
      showCollapse: true,
      collapseDirection: '',
      viewLeftBarList: [
        {
          tabName: 'view-detail',
          disabled: true,
          tabLabel: '',
          tabShow: true,
        }
      ],
      leftActiveTab: 'view-detail',
      formCellCount: 1
    }
  },
  computed: {
    viewLayout() {
      return this.baseLayout
    },
    layoutTabBarList() {
      const tabs = this.buildTabs();
      const newArr = tabs.map(x => {
        return {
          tabName: x.component,
          disabled: true,
          tabLabel: x.displayName,
          tabShow: true,
        }
      })

      return this.viewLeftBarList.concat(newArr);
    },
    // 是否显示返回按钮
    allowBack(){
      let allow = true;

      // 如果带入noHistory参数，则不显示
      let viewUrl = url.parse(window.location.href, true);
      if(viewUrl.query.noHistory) return false;

      // 验证路径
      let path = window.location.pathname;
      if(path.indexOf(RESOURCE_PREFIX) > -1) path = path.replace(RESOURCE_PREFIX, '')
      let disablePathReg = [/^\/product\/detail\/\S+$/];
      if(disablePathReg.some(reg => reg.test(path))) return false;

      return allow;
    },
    // 是否允许删除产品模板
    allowDeleteProductTemplate() {
      return (this.allowEditProduct && this.permission.PRODUCT_MODULE_DELETE);
    },
    /** 
     * 满足以下条件允许编辑产品模板
     * 1. 产品模板没有被删除
     * 2. 有产品编辑权限 或 客户负责人
     */
    allowEditProduct() {
      return (!this.isDelete && (this.hasEditProductAuth || this.isCustomerManager));
    },
    // 字段列表
    fields() {
      let fields = (this.fieldsInfo || []).sort((a, b) => a.orderId - b.orderId).filter(field => {
        return field.fieldName !== 'customer' && field.fieldName !== 'qualityInfo' && field.fieldName !== 'serviceProviders'
      });

      let allFields = [
        ...fields,
        {
          displayName: '',
          formType: 'separator'
        },
        {
          displayName: this.$t('common.base.createUser'),
          fieldName: 'createUser',
          formType: 'user',
          isSystem: 1,
        }, 
        {
          displayName: this.$t('common.base.createTime'),
          fieldName: 'createTime',
          formType: 'text',
          isSystem: 1,
        }
      ];

      return allFields;
    },
    /** 
     * 是否有编辑产品权限，需要满足以下条件之一：
     * 
     * 1. 编辑产品全部权限： 全部产品
     * 2. 编辑产品团队权限： 创建人没有团队的产品都可编辑，有团队的按团队匹配。 包含个人权限
     * 3. 编辑产品个人权限： 自己创建的产品 或 客户负责人的产品
     */
    hasEditProductAuth(){
      let productTemplate = this.productTemplate;
      let loginUserId = (this.loginUser && this.loginUser.userId) || '';
      return AuthUtil.hasAuthWithDataLevel(this.permission, 'PRODUCT_MODULE_EDIT', 
        // 团队权限判断
        () => {
          let tags = Array.isArray(productTemplate.tags) ? productTemplate.tags : [];
          // 无团队则任何人都可编辑
          if(tags.length == 0) return true;

          let loginUserTagIds = this.initData.loginUser.tagIds || [];
          return tags.some(tag => loginUserTagIds.indexOf(tag.id) >= 0);
        }, 
        // 个人权限判断
        () => {
          return productTemplate.createUser == loginUserId
        }
      );
    },
    /**
     *  当前用户是否是该客户负责人
     *  客户负责人用于和客户创建人相同权限
     */
    isCustomerManager() {
      return this.loginUser.userId === this.productTemplate.customerManager;
    },
    /** 
     * 产品模板是否被删除
     * 在产品模板删除时不允许做任何操作，只能查询 
     * 所有操作的权限应该以此为基础
     */
    isDelete(){
      return (this.productTemplate.isDelete == null || this.productTemplate.isDelete === 1);
    },
    // 当前用户的权限
    permission() {
      return (this.initData && this.initData.loginUser && this.initData.loginUser.authorities) || {};
    },
    /** 子组件所需的数据 */
    propsForSubComponents() {
      return {
        allowEditProduct: this.allowEditProduct,
        isDelete: this.isDelete,
        loginUser: this.initData.loginUser,
        productTemplate: this.productTemplate,
        productCount: this.productCount || 0,
        productTemplateId: this.productTemplateId
      };
    },
    productTemplateId() {
      let href = window.location.pathname;
      let path = '/product/detail/';
      let index = 0;

      if(href.indexOf(path) >= 0) {
        index = href.indexOf(path);
        return href.substr(index + path.length);
      }
      return '';
    },
    leftComponentTab() {
      return this.viewLayout === 1 && this.leftActiveTab == 'view-detail' ? this.currentTab : this.leftActiveTab;
    }
  },
  async mounted() {
    this.loading = true;

    this.productCount = (this.initData && this.initData.productCount) || 0;
    this.loginUser = (this.initData && this.initData.loginUser) || {};
    
    await this.initFormBuilderCellCount();
    this.getProductFieldsReq();
    this.fetchProductTemplate();
    
  },
  methods: {
    async initFormBuilderCellCount(){
      try {
        const { getSystemViewLayout } = useStateSystemViewLayout()
        const count = await getSystemViewLayout()
        this.baseLayout = count.baseLayout || 2;
        this.formCellCount = count.formCellCount || 1;
      }catch(e) {
        console.log(e)
      }
    },
    openBaseLayoutModal() {
      this.$refs.bizLayoutModal.open()
    },
    changeViewDetailLayout(type, columns) {
      this.leftActiveTab = 'view-detail' 
      this.baseLayout = type
      if(type === 2) {
        this.currentTab = ProductTemplateInfoRecord.name;
      }
      this.formCellCount = columns * 1
      this.setBaseLayoutStorage()
    },
    tabBarChangeItem(item){
      if(this.viewLayout === 1) {
        this.leftActiveTab = item.tabName;
      } else {
        this.currentTab = item.tabName;
      }
    },
    // 构建tab
    buildTabs() {
      return [
        {
          title: this.$t('product.detail.tabs.tab3'),
          displayName: `${this.$t('product.detail.tabs.tab3')}(${this.recordCount || 0})`,
          component: ProductTemplateInfoRecord.name,
          slotName: 'record-tab',
          isSystem: 1,
          show: true,
        },
        {
          title: this.$t('product.detail.tabs.tab10'),
          displayName: `${this.$t('product.detail.tabs.tab10')}(${this.productCount || 0})`,
          component: ProductTemplateRelatedProductTable.name,
          isSystem: 1,
          show: true
        }
      ].filter(tab => tab.show);
    },
    // 删除产品模板
    async deleteProductTemplate() {
      const confirm = await platform.confirm(this.$t('product.productTemplate.tips.tip3'));
      if(!confirm) return

      try {
        this.loading = true;
        let result = await productTemplateDelete(this.productTemplateId);
        const isSucc = (result.status == 0);

        this.$platform.notification({
          title: isSucc ? this.$t('product.productTemplate.tips.tip4') : this.$t('product.productTemplate.tips.tip5'),
          message: !isSucc && result.message,
          type: isSucc ? 'success' : 'error',
        });

        if(isSucc) {
          const id = window.frameElement.dataset.id;
          const fromId = window.frameElement.getAttribute('fromid');
          this.$platform.closeTab(id);
          this.$platform.refreshTab(fromId);
        }
        this.loading = false;

      } catch(err) {
        console.log(`productDelete err ${err}`)
      }
    },
    // 获取产品模板数据
    fetchProductTemplate() {
      const id = this.productTemplateId;
      getProductTemplate(id).then(result => {

        this.productTemplate = Object.freeze(result);
        this.viewLeftBarList[0].tabLabel = this.productTemplate?.name || '';
        this.loading = false;

        // this.tabs = this.buildTabs();

      })
        .catch(err => console.error(err))
    },
    goBack() {
      parent.frameHistoryBack(window);
    },
    // 跳转编辑
    goEdit() {
      window.location.href = `${this.$resourcePrefix}/product/edit/${this.productTemplateId}`;
    },
    // 信息动态数量变化
    recordCountChange(count) {
      this.recordCount = count;
      this.tabs = this.buildTabs();
    },
    selectTab(tab) {
      this.currentTab = tab;
    },
    // 获取产品表单属性列表
    getProductFieldsReq() {
      getProductFields({isFromSetting:false}).then((res)=>{
        const { status, data, message } = res;
        if( status == 0 ){
          this.fieldsInfo = data;
        }
      }).catch(error=>{});
    },
    getBtnsTrackData(id, data) {
			return this.$track.formatParams(id, data, 'DETAIL_BTNS_GROUP')
		},
    rightActiveTabClick(tab) {
      const title = tab.title
      // tab.isSystem && 
      this.$track.clickStat(this.$track.formatParams('DETAIL_ADD_ONS_TABS', title))
    }
  },
  components: {
    [ProductTemplateInfoRecord.name]: ProductTemplateInfoRecord,
    [ProductTemplateRelatedProductTable.name]: ProductTemplateRelatedProductTable,
    BaseTileLayoutTabBar,
  }
}
</script>

<style lang="scss">

  html, body, .product-template-view-container {
    height: auto;
  }

  body {
    margin: 12px;
    min-width: 1100px;
    overflow-x: auto;
  }

  .product-template-view-container {
    // background: #fff;
    border-radius: 3px;
    // box-shadow: 0 1px 4px rgba(216,216,216, .65);

    display: flex;
    flex-flow: column nowrap;
  }

  .product-template-tool-bar {
    border-bottom: 1px solid #f2f2f2;
    color: $text-color-regular;

    display: flex;
    justify-content: space-between;
    
    font-size: 14px;

    .btn-text {
      padding: 5px 12px;
      .iconfont{
        font-size: 14px;
      }
    }
  }

  .product-template-toolbar {
    padding: 14px 16px;
    margin-bottom: 12px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.1);
  }


  .product-template-detail {
    background: #fff;
    height: auto;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.1);
    min-height: calc(100vh);

    .form-view{
      border-right: 1px solid #f2f2f2;
      flex: 1;
      padding-top: 5px;
      overflow-y: auto;
    }
  }

  .product-template-name{
    @include backgroundColorPrimaryLight9();
    color: $text-color-primary;

    padding: 13px 20px;
    min-height: 50px;
    margin: 0;

    position: relative;

    font-size: 16px;
    font-weight: 500;

    @include text-ellipsis();

    span{
      white-space: nowrap;
      vertical-align: middle;
    }

    .iconfont {
      position: absolute;
      right: 5px;
      bottom: 15px;

      @include fontColor();

      font-size: 12px;

      &:hover {
        cursor: pointer;
      }
    }

    &.product-template-name-expand{
      span{
        white-space: normal;
      }

      .iconfont{
        transform: rotateZ(-180deg);
      }
    }

    .product-template-name-delete,
    .product-template-name-disable{
      border-radius: 4px;
      color: #fff;

      display: inline-block;
      height: 18px;
      padding: 0 5px;

      font-size: 12px;
      line-height: 18px;
      font-weight: 400;

      vertical-align: middle;
      cursor: default;
    }

    .product-template-name-delete{
      background-color: $color-danger;
    }
    .product-template-name-disable{
      background-color: #ffc107;
    }
  }

  .theme-default .product-template-name{
    background-color: #FAFAFA;
  }

  .product-template-relation {
    background: #fff;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.1);
    height: 100%;
    flex: 7;
  }

  .product-template-relation-content {
    height: calc(100% - 50px);
    overflow: auto;
  }

  .action-btn {
    .el-dropdown-btn {
      @include backgroundColorPrimaryLight9();
      border-radius: 2px;
      color: $text-color-primary;

      display: inline-block;
      padding: 0 15px;
      margin-left: 10px;

      line-height: 34px;
      .iconfont {
        font-size: 12px;
        line-height: 12px;

        margin-right: 3px;
      }

      &:hover {
        @include backgroundColor();
        color: #fff;
        cursor: pointer;
      }
    }

    .base-button {
      margin-left: 10px;
    }
  }
</style>
<style scoped lang="scss">
.detail-main-content {
  border-radius: 4px;
  display: flex;
  flex-flow: row nowrap;
  flex: 1;
  position: relative;
  min-height: calc( 100vh - 98px);
  .collapse-right {
    height: 40px;
    line-height: 40px;
    padding-left: 12px;
    color: $text-color-regular;
    border-bottom: 2px solid $color-border-l2;
  }
}
::v-deep .base-collapse {
  min-height: calc(100vh - 88px);
  .base-collapse-right, .base-collapse-left, .resize-bar {
    height: auto
  }
}

.product-template-left-layout {
  height: 85vh;
  background-color: #fff;
}
</style>